package com.android.webrtcsdkdev.net

import android.text.TextUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.net.UnknownHostException
import java.util.Objects

/**

 * @Author : wy

 * @Time : On 2024/10/8 16:05

 * @Description : ApiJavaClient

 */
object ApiJavaClient {
    const val TAG = "ApiJavaClient"

    @JvmStatic
    fun createGroupControl(master_instance_id: String, slave_instance_ids:ArrayList<String>, callback: ICallback<Any>?) {
        val map = HashMap<String, Any>()
        map["master_instance_id"] = master_instance_id
        map["slave_instance_ids"] = slave_instance_ids

        GlobalScope.loadHttp(
            request = { ApiClient.getApiService().createGroupControl(map) },
            response = {
               // i(TAG, "appLogin res: $it")
                callback?.onSuccess(it)
            },
            error = { code: String, msg: String -> callback?.onFailed(code, msg) })
    }


    /**
     * 群控会话ID :session_id
     */
    fun cancelGroupControl(session_id: String, callback: ICallback<Any>?) {
        val map = HashMap<String, Any>()
        map["session_id"] = session_id


        GlobalScope.loadHttp(
            request = { ApiClient.getApiService().cancelGroupControl(map) },
            response = {
                // i(TAG, "appLogin res: $it")
                callback?.onSuccess(it)
            },
            error = { code: String, msg: String -> callback?.onFailed(code, msg) })
    }


    fun <T> CoroutineScope.loadHttp(
        // 默认实现{}，即参数可空
        start: () -> Unit = {},
        // suspend 修饰的函数，返回值ResultData<T>，没有默认实现，即参数不可空
        request: suspend CoroutineScope.() -> ResultData<T>,
        // 函数的参数为T，没有默认实现，即参数不可空
        response: (T) -> Unit,
        error: (String, String) -> Unit = { code: String, msg: String -> },
        end: () -> Unit = {}
    ) {
        // 在主线程(Dispatchers.Main)执行
        launch(Dispatchers.Main) {
            try {
                // 1.函数开始执行，先调用start()方法，给View做准备工作，如：显示loading
                start()
                // 2.发起网络请求
                val data = request()
                if (data.status == 0) {
                    // 3.请求成功，返回响应
                    if (data.data == null){
                        data.data = "" as T
                    }
                    data.data?.let { response(it) }
                } else {
                    // 4.请求失败，调用error()
                    val msg = if (TextUtils.isEmpty(data.message)) "Server connection failed!" else data.message
                    error(data.status.toString(), msg)
                }
            } catch (e: Exception) {
                // 可根据具体异常显示具体错误提示
                when (e) {
                    is UnknownHostException -> error("400", "Server connection failed!")
                    else -> {
                        val msg = if (TextUtils.isEmpty(e.message)) "Server connection failed!" else e.message
                        error("400", msg!!)
                    }
                }
            } finally {
                end()
            }
        }
    }
}